import re
from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from goods.models import SKU
from celery_tasks.email.tasks import send_verify_email
from users.models import User, Address
from . import constants

# 创建用户
class CreateUserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='登录状态token', read_only=True)  # 增加token字段

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'password2', 'sms_code', 'mobile', 'allow', 'token')
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            },

        }

    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式不正确')
        return value

    def validate_allow(self, value):
        if not value:
            raise serializers.ValidationError('用户未同意')
        return value

    def validate(self, attrs):
        password = attrs['password']
        password2 = attrs['password2']
        if password != password2:
            raise serializers.ValidationError('两次密码输入不一致')
        # 判断短信验证码
        redis_conn = get_redis_connection('verify_codes')
        mobile = attrs['mobile']
        real_mobile = redis_conn.get("sms_%s" % mobile)
        if not real_mobile:
            raise serializers.ValidationError('无效的短信验证码')
        sms_code = attrs['sms_code']
        real_mobile = real_mobile.decode()
        if real_mobile != sms_code:
            raise serializers.ValidationError('短信验证码错误')

        return attrs

    def create(self, validated_data):
        # 删除表中没有的字段
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        # user = User.objects.create(**validated_data)
        # user = User.objects.create(username=xxx, password=xxx, mobile=xxx)

        # 给密码进行加密
        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user


# 获取单一用户信息
class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        # 默认不指定　read_only　或者 write_only　会既序列化又反序列化
        fields = ('id', 'username', 'username', 'email', 'email_active')


# 增加用户email字段信息
class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'email')
        extra_kwargs = {
            # required 反序列化时必须传入
            'email': {'required': True}
        }

    # 保存邮箱的同时，我们要发送邮件, 所以重写update方法
    # 基础班讲的是,如果用户传过来的有instance,也有validated_data　说明是要修改数据
    # instance是模型对象，validated_data是经过验证的数据
    def update(self, instance, validated_data):
        email = validated_data['email']
        instance.email = email
        instance.save()
        verify_url = instance.generate_verify_email_url()
        # 发送邮件
        send_verify_email.delay(email, verify_url)
        return instance


# 创建用户地址
class UserAddressSerializer(serializers.ModelSerializer):
    # 返回__str__方法return返回值，而不是id (这里不写的话，返回的就是id)
    # ppp = serializers.PrimaryKeyRelatedField
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'create_time', 'update_time', 'is_deleted')

    # 验证手机号
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式不正确')
        return value

    # 把未序列化的user数据添加到模型对象中
    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


# 添加地址标题
class AddressTitleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = ('title', )


class AddUserBrowsingHistorySerializer(serializers.Serializer):
    """
    添加用户浏览记录序列化器
    """
    sku_id = serializers.IntegerField(label='商品SKU编号', min_value=1)

    def validated_sku_id(self, value):
        """
        :param value: 需要验证的字段, 验证传入的sku_id是否存在
        :return: value
        """
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('该商品不存在')
        else:
            return value

    def create(self, validated_data):
        """
        如果继承的是Serializer，默认是没有实现create方法的，Modelserializer有默认实现
        但是我们这里操作的是redis数据库，不使用系统默认的操作mysql数据库的方法，要自己写
        :param validated_data: 已经验证过的数据
        :return: 数据（这里操作的redis，若操作的是mysql，需要返回instance,模型对象）
        """
        user_id = self.context['request'].user.id
        sku_id = validated_data['sku_id']
        redis_conn = get_redis_connection('history')
        pl = redis_conn.pipeline()
        # 先删除存在的sku_id (0表示删除所有, )
        pl.lrem('history_%s' % user_id, 0, sku_id)
        # 添加本次浏览的商品sku_id
        pl.lpush('history_%s' % user_id, sku_id)
        # 只保存５条记录  ltrim只保存列表中的前五条数据，其余的删掉
        pl.ltrim('history_%s' % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT-1)
        pl.execute()
        return validated_data


class SKUSerializer(serializers.ModelSerializer):
    """ 获取浏览记录的真是数据库数据　"""
    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'comments')

